package com.cy.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.cy.bean.AdminList;
import com.cy.bean.UserList;
import com.cy.util.ConnectionFactory;

public class LoginDaoImpl implements LoginDao {

	@Override
	public UserList findUser(String username, String password) {
		Connection conn = ConnectionFactory.getConnection();
		PreparedStatement psmt = null;
		ResultSet rs = null;
		try {
			String sql = "select * from user where username=? and password=? and state=1";
			psmt = conn.prepareStatement(sql);
			psmt.setString(1, username);
			psmt.setString(2, password);
			rs = psmt.executeQuery();
			UserList user = new UserList();
			while (rs.next()) {
				user.setId(rs.getInt("id"));
				user.setName(rs.getString("name"));
				user.setSex(rs.getInt("sex"));
				user.setAge(rs.getInt("age"));
				user.setUsername(rs.getString("username"));
				user.setPassword(rs.getString("password"));
				user.setEmail(rs.getString("email"));
				user.setState(rs.getInt("state"));
				return user;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			ConnectionFactory.close(conn, psmt, rs);
		}
		return null;
	}

	@Override
	public AdminList findAdmin(String username, String password) {
		Connection conn = ConnectionFactory.getConnection();
		PreparedStatement psmt = null;
		ResultSet rs = null;
		try {
			String sql = "select * from admin where username=? and password=?";
			psmt = conn.prepareStatement(sql);
			psmt.setString(1, username);
			psmt.setString(2, password);
			rs = psmt.executeQuery();
			AdminList admin = new AdminList();
			while (rs.next()) {
				admin.setId(rs.getInt("id"));
				admin.setUsername(rs.getString("username"));
				admin.setPassword(rs.getString("password"));
				return admin;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			ConnectionFactory.close(conn, psmt, rs);
		}
		return null;
	}

}
